package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.entity.Result;
import com.itheima.service.MemeberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.Oneway;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员服务业务逻辑处理层
 * @author wangxin
 * @version 1.0
 */
@Service(interfaceClass = MemeberService.class)
@Transactional
public class MemeberServiceImpl implements MemeberService {

    @Autowired
    private MemberDao memberDao;

    /**
     * 根据年月获取累计会员数量
     * @param listMonth
     * @return
     */
    @Override
        public List<Integer> findMemberCountByMonth(List<String> listMonth) {
            //定义list集合存放会员数量
            List<Integer> memberCount = new ArrayList<>();
            if(listMonth != null && listMonth.size()>0){
                for (String yearMonth : listMonth) {
                    //2020-02 select count(*) from t_member where regTime <= '2020-02-31'
                    yearMonth = yearMonth+"-31";
                    Integer count = memberDao.findMemberCountBeforeDate(yearMonth);
                    memberCount.add(count);
                }
            }
        return memberCount;
    }

    @Override
    public Result get(Map map) {
        List<Integer> memberCount = findMemberCountByMonth(o(map));
        Map<String, Object> data = new HashMap<>();
        data.put("months", o(map));
        data.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);

    }

    private List<String> o(Map map){
        String orderDate1 = (String) map.get("orderDate1");
        String orderDate2 = (String) map.get("orderDate2");
        String[] oder1 = orderDate1.split("-");
        String[] oder2 = orderDate2.split("-");
        //获取开始的年份
        int startYear = Integer.parseInt(oder1[0]);
        //获取结束的年份
        int endYear = Integer.parseInt(oder2[0]);
        //获取开始的月份
        int startMonth = Integer.parseInt(oder1[1]);
        //获取结束月份
        int endMonth = Integer.parseInt(oder2[1]);
        List<String> months = new ArrayList<>();
        //初始化
        int month = 1;
        for (int i = startYear; i <= endYear; i++) {
            //如果是开始年月就是开始月 否则
            if (i == startYear) {
                month = startMonth;
            }
            else {
                month = 1;
            }
            //循环
            for (int j = month; j <= 12; j++) {
                if (i == endYear && j > endMonth) {
                    break;
                }
                months.add(String.valueOf(i) + "." + String.valueOf(j));
            }
        }
        return months;
    }
}
